//
//  InExContentViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 10/22/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "InExContentViewController.h"

@interface InExContentViewController ()

@end

@implementation InExContentViewController
@synthesize incomeExpenseTableView;
@synthesize popUpView;
@synthesize currentDate;
@synthesize startDate,endDate;
@synthesize isCategoryMode;
@synthesize incomeTotal;
@synthesize expenseTotal;
@synthesize totalMoneyView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    //Get Income and Expense Array
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:currentDate];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:currentDate];
    expenseRowNumber = [expenseArray count];
    // Do any additional setup after loading the view from its nib.
    
    incomeSum = 0;
    expenseSum = 0;
    for(Income *income in incomeArray) {
        incomeSum += income.i_amount.floatValue;
    }
    for(Expense *expense in expenseArray) {
        expenseSum+= expense.e_amount.floatValue;
    }
    
    incomeTotal.text = [NSString stringWithFormat:@"%f",incomeSum];
    expenseTotal.text = [NSString stringWithFormat:@"%f",expenseSum];
    
    
    [UIView animateWithDuration:2 animations:^{
        [UIView animateWithDuration:1 delay:0 options:UIViewAnimationCurveEaseOut animations:^{
            totalMoneyView.frame = CGRectMake(0, 0, 320, 23);
        }completion:nil];
         totalMoneyView.alpha = 1;
        incomeExpenseTableView.alpha = 1;}];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadIncomeExpenseTable :) name:@"reloadIncomeExpenseTable" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addExpense_OnSuccess :) name:@"addExpense_OnSuccess" object:nil];
    
}

- (void)viewDidUnload
{
    [self setIncomeExpenseTableView:nil];
    [self setPopUpView:nil];
    [self setIncomeTotal:nil];
    [self setExpenseTotal:nil];
    [self setTotalMoneyView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table View Delegate

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    //
    //    NSMutableArray *incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:currentDate];
    //    NSMutableArray *expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:currentDate];
    //    NSLog(@"Number of row %d",[incomeArray count]+[expenseArray count]);
    if(!isCategoryMode) {
        return  [incomeArray count]+[expenseArray count];
    } else {
        if(section == 0) {
            return [incomeArray count];
        } else {
            return [expenseArray count];
        }
    }
    
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    if(!isCategoryMode){
        return  1;
    } else {
        return 2;
    }
    
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,320,30)];
    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sub_navbar_bg.png"]];
    //-------------------Format Date Section --------------------//
    
    
    UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 200, 20)];
    if(!isCategoryMode) {
        sectionTitleLabel.text = @"Income & Expense Diary";
    } else {
        if(section == 0) {
            sectionTitleLabel.text = @"Income Diary";
        }else {
            sectionTitleLabel.text = @"Expense Diary";
        }
    }
    
    
    
    sectionTitleLabel.textColor = [UIColor whiteColor];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14];
    sectionTitleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:sectionTitleLabel];
    
    return headerView;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellInditifier = @"CellInditifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInditifier] ;
    
    UIImageView *imageView;
    UILabel *titleLabel;
    UITextField *amountTextField;
    UILabel *dayLabel;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    
    if( cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInditifier];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 40, 40)];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 100;
        [cell addSubview:imageView];
        
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 200, 20)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor colorWithRed:99.0/255.0 green:182.0/255.0 blue:67.0/255.0 alpha:1];
        titleLabel.tag = 200;
        [cell addSubview:titleLabel];
        
        amountTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 10, 280, 20)];
        amountTextField.textColor = [UIColor whiteColor];
        amountTextField.backgroundColor = [UIColor clearColor];
        amountTextField.font = [UIFont systemFontOfSize:12];
        amountTextField.tag = 300;
        amountTextField.enabled = NO;
        [cell addSubview:amountTextField];
        
        dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 35, 200, 10)];
        dayLabel.backgroundColor = [UIColor clearColor];
        dayLabel.textColor = [UIColor blackColor];
        dayLabel.tag = 500;
        dayLabel.font = [UIFont italicSystemFontOfSize:12.0f];
        [cell addSubview:dayLabel];
    }
    
    imageView = (UIImageView*) [cell viewWithTag:100];
    titleLabel = (UILabel*) [cell viewWithTag:200];
    amountTextField = (UITextField*)[cell viewWithTag:300];
    dayLabel = (UILabel*)[cell viewWithTag:500];
    
    if(!isCategoryMode) {
        if( indexPath.row < [incomeArray count]) {
            Income *tempIncome = [incomeArray objectAtIndex:indexPath.row];
            NSLog(@"%@",tempIncome.i_name);
            titleLabel.text = tempIncome.i_name;
            imageView.image = [UIImage imageNamed:tempIncome.iToIncomeType.it_image];
            
            amountTextField.text = [NSString stringWithFormat:@"%d",[tempIncome.i_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempIncome.i_date];
        } else {
            NSLog(@"indexPath.row = %d",indexPath.row);
            Expense *tempExpense = [expenseArray objectAtIndex:indexPath.row - [incomeArray count]];
            titleLabel.text = tempExpense.e_name;
            imageView.image = [UIImage imageNamed:tempExpense.eToExpenseType.et_image];
            
            amountTextField.text = [NSString stringWithFormat:@"-%d",[tempExpense.e_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempExpense.e_date];
        }
        
    } else {
        if(indexPath.section == 0) {
            Income *tempIncome = [incomeArray objectAtIndex:indexPath.row];
            NSLog(@"%@",tempIncome.i_name);
            titleLabel.text = tempIncome.i_name;
            imageView.image = [UIImage imageNamed:tempIncome.iToIncomeType.it_image];
            
            amountTextField.text = [NSString stringWithFormat:@"%d",[tempIncome.i_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempIncome.i_date];
        } else {
            NSLog(@"indexPath.row = %d",indexPath.row);
            Expense *tempExpense = [expenseArray objectAtIndex:indexPath.row];
            titleLabel.text = tempExpense.e_name;
            imageView.image = [UIImage imageNamed:tempExpense.eToExpenseType.et_image];
            
            amountTextField.text = [NSString stringWithFormat:@"-%d",[tempExpense.e_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempExpense.e_date];
        }
    }
    
    CGSize amountTextFieldSize = [amountTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    amountTextField.frame = CGRectMake(290-amountTextFieldSize.width,10 , amountTextFieldSize.width+15, 20);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    currentIndexPath = indexPath;
    CGRect rectOfCellInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rectOfCellInSuperview = [tableView convertRect:rectOfCellInTableView toView:[tableView superview]];
    
    
    NSLog(@"%f %f",rectOfCellInSuperview.origin.x,rectOfCellInSuperview.origin.y);
    
    if (!isCategoryMode) {
        if(indexPath.row <incomeRowNumber) {
            currentIncome = [incomeArray objectAtIndex:indexPath.row];
        } else {
            currentExpense = [expenseArray objectAtIndex:indexPath.row-incomeRowNumber];
        }
    } else {
        if(indexPath.section == 0) {
            currentIncome = [incomeArray objectAtIndex:indexPath.row];
        } else {
            currentExpense = [expenseArray objectAtIndex:indexPath.row];
        }
    }
    
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popUpView contentSize:CGSizeMake(170, 60)];
		
        [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		//[popup release];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}
}

#pragma mark -----------------Popup-----------------
- (void)didTouchPopupView:(SNPopupView*)sender {
    //	DNSLogMethod
    //	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}

#pragma mark ----------NSNotification Center ------------

-(void)reloadIncomeExpenseTable: (NSNotification*)notification {

    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if(!isCategoryMode){
        incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:currentDate];
        incomeRowNumber = [incomeArray count];
        expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:currentDate];
        expenseRowNumber = [expenseArray count];
    }else {
        incomeArray = [DataBaseAccess getAllIncomeByWallet:delegate.currentWallet];
        incomeRowNumber = [incomeArray count];
        expenseArray = [DataBaseAccess getAllExpenseByWallet:delegate.currentWallet];
        expenseRowNumber = [expenseArray count];
    }
    
    
    
    [incomeExpenseTableView reloadData];
    
    
}

-(void) addExpense_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:currentDate];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:currentDate];
    expenseRowNumber = [expenseArray count];
    NSLog(@"%d , %d",incomeRowNumber,expenseRowNumber);
    [incomeExpenseTableView reloadData];
}

#pragma mark ---------------IBAction Delegate----------------------
- (IBAction)editButtonPressed:(id)sender {
    if (!isCategoryMode) {
        if(currentIndexPath.row < incomeRowNumber) {
            AddIncomeViewController *addIncomeView = [[AddIncomeViewController alloc]init];
            addIncomeView.kindOfView = @"Edit";
            addIncomeView.currentIncome = currentIncome;
            [self.navigationController pushViewController:addIncomeView animated:YES];
        } else {
            AddExpenseViewController *addExpenseView = [[AddExpenseViewController alloc]init];
            addExpenseView.kindOfView = @"Edit";
            addExpenseView.currentExpense = currentExpense;
            [self.navigationController pushViewController:addExpenseView animated:YES];
        }
    } else {
        if(currentIndexPath.section == 0) {
            AddIncomeViewController *addIncomeView = [[AddIncomeViewController alloc]init];
            addIncomeView.kindOfView = @"Edit";
            addIncomeView.currentIncome = currentIncome;
            [self.navigationController pushViewController:addIncomeView animated:YES];
        } else {
            AddExpenseViewController *addExpenseView = [[AddExpenseViewController alloc]init];
            addExpenseView.kindOfView = @"Edit";
            addExpenseView.currentExpense = currentExpense;
            [self.navigationController pushViewController:addExpenseView animated:YES];
        }
    }
    [popup dismissModal];
}

- (IBAction)deleteButtonPressed:(id)sender {
    
    if (!isCategoryMode) {
        if(currentIndexPath.row < incomeRowNumber) {
            [DataBaseAccess deleteIncome:[incomeArray objectAtIndex:currentIndexPath.row]];
            [incomeArray removeObjectAtIndex:currentIndexPath.row];
            
        } else {
            [DataBaseAccess deleteExpense:[expenseArray objectAtIndex:currentIndexPath.row -incomeRowNumber]];
            [expenseArray removeObjectAtIndex:currentIndexPath.row-incomeRowNumber];
        }
    } else {
        if(currentIndexPath.section == 0) {
            [DataBaseAccess deleteIncome:[incomeArray objectAtIndex:currentIndexPath.row]];
            [incomeArray removeObjectAtIndex:currentIndexPath.row];
            
        } else {
            [DataBaseAccess deleteExpense:[expenseArray objectAtIndex:currentIndexPath.row]];
            [expenseArray removeObjectAtIndex:currentIndexPath.row];
        }
    }
    
    [popup dismissModal];
    [incomeExpenseTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
}

- (IBAction)viewButtonPressed:(id)sender {
    
    if (!isCategoryMode) {
        if(currentIndexPath.row < incomeRowNumber) {
            ViewIncomeViewController *viewIncomeViewController = [[ViewIncomeViewController alloc]init];
            viewIncomeViewController.currentIncome = currentIncome;
            [self.navigationController pushViewController:viewIncomeViewController animated:YES];
        } else {
            ViewExpenseViewController *viewExpenseViewController = [[ViewExpenseViewController alloc]init];
            viewExpenseViewController.currentExpense = currentExpense;
            [self.navigationController pushViewController:viewExpenseViewController animated:YES];
        }
    } else {
        if(currentIndexPath.section == 0) {
            ViewIncomeViewController *viewIncomeViewController = [[ViewIncomeViewController alloc]init];
            viewIncomeViewController.currentIncome = currentIncome;
            [self.navigationController pushViewController:viewIncomeViewController animated:YES];
        } else {
            ViewExpenseViewController *viewExpenseViewController = [[ViewExpenseViewController alloc]init];
            viewExpenseViewController.currentExpense = currentExpense;
            [self.navigationController pushViewController:viewExpenseViewController animated:YES];
        }
    }
    
    [popup dismissModal];
}

#pragma mark -------------------Reload Data-------------------
-(void) reloadCustomDateTable {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDateFrom:startDate andDateTo:endDate];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDateFrom:startDate andDateTo:endDate];
    expenseRowNumber = [expenseArray count];
    [incomeExpenseTableView reloadData];
    
    incomeSum = 0;
    expenseSum = 0;
    for(Income *income in incomeArray) {
        incomeSum += income.i_amount.floatValue;
    }
    for(Expense *expense in expenseArray) {
        expenseSum+= expense.e_amount.floatValue;
    }
    
    incomeTotal.text = [NSString stringWithFormat:@"%f",incomeSum];
    expenseTotal.text = [NSString stringWithFormat:@"%f",expenseSum];
    
    totalMoneyView.frame = CGRectMake(320, 0, 320, 23);
    [UIView animateWithDuration:1.0 animations:^{
        totalMoneyView.frame = CGRectMake(0, 0, 320, 23);}];
}

-(void) reloadDailyTable {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:currentDate];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:currentDate];
    expenseRowNumber = [expenseArray count];
    [incomeExpenseTableView reloadData];
}

-(void) reloadTableByCategory {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByWallet:delegate.currentWallet];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByWallet:delegate.currentWallet];
    expenseRowNumber = [expenseArray count];
    [incomeExpenseTableView reloadData];
}
@end
